#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用真实应用创建真实HAI实例
"""

import os
import sys
import json
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def create_real_instance_with_real_app():
    """使用真实应用创建真实HAI实例"""
    print("🏗️ 使用真实应用创建真实HAI实例")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        print("✅ HAI客户端创建成功")
        
        # 使用真实的应用ID
        real_app_id = "app-2xilycjt"  # DeepSeek-R1 AnythingLLM
        
        # 创建实例请求
        req = models.RunInstancesRequest()
        
        # 设置必需参数
        req.ApplicationId = real_app_id
        req.InstanceName = "real-hai-instance"
        req.InstanceCount = 1
        
        # 尝试不同的BundleType
        bundle_types_to_try = [
            "HAI_V100",
            "HAI_T4", 
            "HAI_GTX1080",
            "HAI_RTX3080",
            "HAI_V100_1C",
            "HAI_V100_2C",
            "HAI_V100_4C",
            "HAI_T4_1C",
            "HAI_T4_2C",
            "HAI_GTX1080_1C",
            "HAI_GTX1080_2C",
            "HAI_RTX3080_1C",
            "HAI_RTX3080_2C"
        ]
        
        print(f"📋 实例创建参数:")
        print(f"  ApplicationId: {req.ApplicationId}")
        print(f"  InstanceName: {req.InstanceName}")
        print(f"  InstanceCount: {req.InstanceCount}")
        
        # 尝试不同的BundleType
        for bundle_type in bundle_types_to_try:
            try:
                print(f"\n🧪 尝试BundleType: {bundle_type}")
                req.BundleType = bundle_type
                
                # 执行创建实例
                print(f"🚀 开始创建实例...")
                resp = client.RunInstances(req)
                
                print(f"✅ 实例创建成功!")
                print(f"请求ID: {resp.RequestId}")
                
                if hasattr(resp, 'InstanceIdSet') and resp.InstanceIdSet:
                    instance_ids = resp.InstanceIdSet
                    print(f"实例ID列表: {instance_ids}")
                    
                    for instance_id in instance_ids:
                        print(f"\n📊 实例详情:")
                        print(f"  实例ID: {instance_id}")
                        print(f"  应用ID: {req.ApplicationId}")
                        print(f"  实例名称: {req.InstanceName}")
                        print(f"  BundleType: {bundle_type}")
                        print(f"  地域: ap-beijing")
                        
                        # 查询实例状态
                        try:
                            status_req = models.DescribeInstancesRequest()
                            status_req.InstanceIds = [instance_id]
                            status_resp = client.DescribeInstances(status_req)
                            
                            if status_resp.InstanceSet:
                                instance_info = status_resp.InstanceSet[0]
                                print(f"  实例状态: {instance_info.InstanceState}")
                                print(f"  创建时间: {instance_info.CreatedTime}")
                                
                        except Exception as e:
                            print(f"  状态查询失败: {e}")
                    
                    return instance_ids[0] if instance_ids else None
                else:
                    print("❌ 未返回实例ID")
                    continue
                    
            except Exception as e:
                print(f"❌ BundleType {bundle_type} 失败: {e}")
                continue
        
        print(f"\n❌ 所有BundleType都失败")
        return None
            
    except Exception as e:
        print(f"❌ 创建实例失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def query_app_details():
    """查询应用详细信息"""
    print("\n🔍 查询应用详细信息")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        # 查询应用详情
        req = models.DescribeApplicationsRequest()
        resp = client.DescribeApplications(req)
        
        if hasattr(resp, 'ApplicationSet') and resp.ApplicationSet:
            for app in resp.ApplicationSet:
                print(f"📱 应用详情:")
                print(f"  应用ID: {app.ApplicationId}")
                print(f"  应用名称: {app.ApplicationName}")
                print(f"  应用状态: {app.ApplicationState}")
                print(f"  创建时间: {app.CreatedTime}")
                
                # 尝试获取更多属性
                attrs = [attr for attr in dir(app) if not attr.startswith('_')]
                for attr in attrs:
                    try:
                        value = getattr(app, attr)
                        if value and attr not in ['ApplicationId', 'ApplicationName', 'ApplicationState', 'CreatedTime']:
                            print(f"  {attr}: {value}")
                    except:
                        pass
                print()
        
        return True
        
    except Exception as e:
        print(f"❌ 查询应用详情失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 使用真实应用创建真实HAI实例")
    print("=" * 60)
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    
    # 查询应用详情
    query_app_details()
    
    # 创建真实实例
    instance_id = create_real_instance_with_real_app()
    
    if instance_id:
        print(f"\n🎉 真实HAI实例创建完成！")
        print(f"\n📋 总结:")
        print(f"✅ 实例ID: {instance_id}")
        print(f"✅ 应用ID: app-2xilycjt")
        print(f"✅ 应用名称: DeepSeek-R1 AnythingLLM")
        print(f"✅ 地域: ap-beijing")
        print(f"✅ 实例名称: real-hai-instance")
        
        print(f"\n🔗 后续操作:")
        print(f"- 可以在腾讯云控制台查看实例详情")
        print(f"- 可以通过API管理实例状态")
        print(f"- 可以部署应用和任务")
        
        return True
    else:
        print(f"\n❌ 真实实例创建失败")
        
        print(f"\n📋 需要的信息:")
        print(f"1. 正确的BundleType")
        print(f"2. 确认应用配置")
        print(f"3. 确认权限配置")
        print(f"4. 确认配额情况")
        
        print(f"\n💡 建议:")
        print(f"- 在腾讯云控制台手动创建一个实例")
        print(f"- 查看实际使用的参数")
        print(f"- 联系腾讯云技术支持")
        
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
